'use client';

import React, { useState, useEffect } from 'react';
import { useCollaboration } from '@/hooks/use-collaboration';
import { useSocket } from '@/hooks/use-socket';
import { 
  Card, 
  CardContent, 
  CardDescription, 
  CardFooter, 
  CardHeader, 
  CardTitle 
} from '@/components/ui/card';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { 
  Users, 
  MessageSquare, 
  Clock, 
  History, 
  Shield, 
  Lock, 
  Unlock,
  RefreshCw
} from 'lucide-react';
import { DocumentVersion } from '@/types/document';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { format } from 'date-fns';
import { toast } from '@/components/ui/use-toast';

interface CollaborationInfoPanelProps {
  projectId: string;
  documentId: string;
  className?: string;
}

interface Collaborator {
  id: string;
  name: string;
  status: 'online' | 'offline' | 'idle' | 'away';
  lastActive?: Date;
  isEditing?: boolean;
  currentBlock?: string;
  role?: string;
  avatar?: string;
}

// 状态颜色映射
const STATUS_COLORS = {
  online: 'bg-green-500',
  offline: 'bg-gray-400',
  idle: 'bg-amber-400',
  away: 'bg-red-400'
};

export function CollaborationInfoPanel({ projectId, documentId, className = '' }: CollaborationInfoPanelProps) {
  const { revisions, editor } = useCollaboration();
  const { socket, isConnected, activeUsers, documentLocks } = useSocket();
  const [activeTab, setActiveTab] = useState('collaborators');
  const [collaborators, setCollaborators] = useState<Collaborator[]>([]);
  const [lastUpdate, setLastUpdate] = useState<Date | null>(null);
  const [documentIsLocked, setDocumentIsLocked] = useState(false);
  const [lockedBy, setLockedBy] = useState<string | null>(null);
  
  // 获取协作者信息
  useEffect(() => {
    if (!isConnected) return;
    
    // 监听用户加入/离开事件
    const handleUserStatus = (data: any) => {
      if (data.projectId !== projectId) return;
      
      // 更新协作者列表
      setCollaborators(prev => {
        // 找到现有用户
        const existingUserIndex = prev.findIndex(u => u.id === data.userId);
        
        if (existingUserIndex >= 0) {
          // 更新现有用户
          const updatedUsers = [...prev];
          updatedUsers[existingUserIndex] = {
            ...updatedUsers[existingUserIndex],
            status: data.status,
            lastActive: new Date(),
            isEditing: data.isEditing || updatedUsers[existingUserIndex].isEditing
          };
          return updatedUsers;
        } else if (data.status === 'online') {
          // 添加新用户
          return [...prev, {
            id: data.userId,
            name: data.userName || 'Unknown User',
            status: data.status,
            lastActive: new Date(),
            isEditing: data.isEditing || false,
            avatar: data.userImage
          }];
        }
        
        return prev;
      });
      
      setLastUpdate(new Date());
    };
    
    // 监听文档锁定状态
    const handleDocumentLock = (data: any) => {
      if (data.projectId !== projectId || data.docId !== documentId) return;
      
      setDocumentIsLocked(true);
      setLockedBy(data.userName);
      setLastUpdate(new Date());
    };
    
    // 监听文档解锁状态
    const handleDocumentUnlock = (data: any) => {
      if (data.projectId !== projectId || data.docId !== documentId) return;
      
      setDocumentIsLocked(false);
      setLockedBy(null);
      setLastUpdate(new Date());
    };
    
    // 监听块编辑状态
    const handleBlockEditing = (data: any) => {
      if (data.projectId !== projectId || data.docId !== documentId) return;
      
      setCollaborators(prev => {
        const existingUserIndex = prev.findIndex(u => u.id === data.userId);
        
        if (existingUserIndex >= 0) {
          // 更新用户编辑状态
          const updatedUsers = [...prev];
          updatedUsers[existingUserIndex] = {
            ...updatedUsers[existingUserIndex],
            isEditing: data.isEditing,
            currentBlock: data.isEditing ? data.blockId : undefined,
            lastActive: new Date()
          };
          return updatedUsers;
        }
        
        return prev;
      });
      
      setLastUpdate(new Date());
    };
    
    // 订阅事件
    const unsubUserStatus = socket?.onUserStatus(handleUserStatus);
    const unsubLock = socket?.onDocumentLocked(handleDocumentLock);
    const unsubUnlock = socket?.onDocumentUnlocked(handleDocumentUnlock);
    const unsubBlockEditing = socket?.onBlockEditing(handleBlockEditing);
    
    // 初始化活跃用户
    if (activeUsers) {
      const initialUsers = activeUsers
        .filter(user => user.projectId === projectId)
        .map(user => ({
          id: user.userId,
          name: user.userName || 'Unknown User',
          status: 'online' as const,
          lastActive: new Date(user.lastActive || Date.now()),
          isEditing: false,
          avatar: user.userImage
        }));
      
      setCollaborators(initialUsers);
    }
    
    // 初始化文档锁定状态
    if (documentLocks) {
      const docLock = documentLocks.find(
        lock => lock.projectId === projectId && lock.docId === documentId
      );
      
      if (docLock) {
        setDocumentIsLocked(true);
        setLockedBy(docLock.userName);
      }
    }
    
    // 清理订阅
    return () => {
      if (unsubUserStatus) unsubUserStatus();
      if (unsubLock) unsubLock();
      if (unsubUnlock) unsubUnlock();
      if (unsubBlockEditing) unsubBlockEditing();
    };
  }, [isConnected, socket, projectId, documentId, activeUsers, documentLocks]);
  
  // 获取用户初始字母（用于头像）
  const getUserInitials = (name: string) => {
    return name
      .split(' ')
      .map(part => part[0])
      .join('')
      .toUpperCase()
      .substring(0, 2);
  };
  
  // 渲染协作者列表
  const renderCollaborators = () => {
    if (collaborators.length === 0) {
      return (
        <div className="py-4 text-center text-muted-foreground">
          <p>暂无其他协作者</p>
        </div>
      );
    }
    
    return (
      <ScrollArea className="h-[300px] pr-4">
        <div className="space-y-2">
          {collaborators.map(collaborator => (
            <div 
              key={collaborator.id} 
              className="flex items-center justify-between p-2 rounded-md hover:bg-muted/50"
            >
              <div className="flex items-center gap-2">
                <div className="relative">
                  <Avatar className="h-8 w-8">
                    {collaborator.avatar ? (
                      <AvatarImage src={collaborator.avatar} alt={collaborator.name} />
                    ) : (
                      <AvatarFallback>{getUserInitials(collaborator.name)}</AvatarFallback>
                    )}
                  </Avatar>
                  <span 
                    className={`absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full ring-2 ring-white ${STATUS_COLORS[collaborator.status]}`}
                  />
                </div>
                <div>
                  <p className="text-sm font-medium">{collaborator.name}</p>
                  {collaborator.isEditing && (
                    <p className="text-xs text-muted-foreground">
                      正在编辑 
                      {collaborator.currentBlock ? ` 块 ${collaborator.currentBlock.substring(0, 8)}...` : ''}
                    </p>
                  )}
                </div>
              </div>
              
              <div className="flex items-center">
                {collaborator.isEditing && (
                  <Badge variant="outline" className="bg-green-100 text-green-800 border-green-200">
                    <RefreshCw className="h-3 w-3 mr-1 animate-spin" />
                    编辑中
                  </Badge>
                )}
                {collaborator.role && (
                  <Badge variant="outline" className="ml-2 bg-blue-100 text-blue-800 border-blue-200">
                    <Shield className="h-3 w-3 mr-1" />
                    {collaborator.role}
                  </Badge>
                )}
              </div>
            </div>
          ))}
        </div>
      </ScrollArea>
    );
  };
  
  // 渲染版本历史
  const renderHistory = () => {
    if (!revisions || revisions.length === 0) {
      return (
        <div className="py-4 text-center text-muted-foreground">
          <p>暂无版本历史</p>
        </div>
      );
    }
    
    return (
      <ScrollArea className="h-[300px] pr-4">
        <div className="space-y-2">
          {revisions.slice(0, 10).map((revision, index) => {
            // 确保revision符合DocumentVersion类型
            const typedRevision: DocumentVersion = {
              id: revision.revision?.id || `temp-${index}`,
              content: revision.revision?.content || {},
              version: revision.revision?.version || 0,
              createdAt: revision.timestamp ? new Date(revision.timestamp).toISOString() : new Date().toISOString(),
              createdBy: revision.revision?.createdBy || { id: '', name: '未知用户' },
              message: revision.revision?.message
            };
            
            return (
              <div 
                key={typedRevision.id} 
                className="p-2 rounded-md hover:bg-muted/50"
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <History className="h-4 w-4 text-muted-foreground" />
                    <span className="text-sm font-medium">
                      {format(new Date(typedRevision.createdAt), 'yyyy-MM-dd HH:mm')}
                    </span>
                  </div>
                  <span className="text-xs text-muted-foreground">
                    v{typedRevision.version}
                  </span>
                </div>
                {typedRevision.message && (
                  <p className="text-xs text-muted-foreground mt-1 ml-6">
                    {typedRevision.message}
                  </p>
                )}
                <p className="text-xs text-muted-foreground mt-1 ml-6">
                  by {typedRevision.createdBy?.name || '未知用户'}
                </p>
              </div>
            );
          })}
          
          {revisions.length > 10 && (
            <div className="text-center pt-2">
              <Button 
                variant="link" 
                size="sm" 
                className="text-xs"
                onClick={() => toast({
                  title: '历史版本',
                  description: '请使用文档历史面板查看完整版本历史'
                })}
              >
                查看更多版本历史...
              </Button>
            </div>
          )}
        </div>
      </ScrollArea>
    );
  };
  
  // 渲染锁定状态
  const renderLockStatus = () => (
    <div className="flex items-center gap-2 py-2">
      {documentIsLocked ? (
        <>
          <Lock className="h-4 w-4 text-amber-500" />
          <span className="text-sm">
            文档当前被 <span className="font-medium">{lockedBy || '未知用户'}</span> 锁定编辑
          </span>
        </>
      ) : (
        <>
          <Unlock className="h-4 w-4 text-green-500" />
          <span className="text-sm">文档未锁定，可以自由编辑</span>
        </>
      )}
    </div>
  );
  
  return (
    <Card className={`overflow-hidden ${className}`}>
      <CardHeader className="bg-muted/30 pb-2">
        <div className="flex items-center justify-between">
          <CardTitle className="text-base">协作信息</CardTitle>
          <CardDescription>
            {lastUpdate ? `最后更新: ${format(lastUpdate, 'HH:mm:ss')}` : '实时状态'}
          </CardDescription>
        </div>
      </CardHeader>
      
      <CardContent className="p-0">
        <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
          <TabsList className="w-full grid grid-cols-2">
            <TabsTrigger value="collaborators">
              <Users className="h-4 w-4 mr-1" />
              协作者 ({collaborators.length})
            </TabsTrigger>
            <TabsTrigger value="history">
              <History className="h-4 w-4 mr-1" />
              历史记录
            </TabsTrigger>
          </TabsList>
          
          <TabsContent value="collaborators" className="pt-4 px-4">
            {renderLockStatus()}
            {renderCollaborators()}
          </TabsContent>
          
          <TabsContent value="history" className="pt-4 px-4">
            {renderHistory()}
          </TabsContent>
        </Tabs>
      </CardContent>
      
      <CardFooter className="flex justify-between bg-muted/30 py-2">
        <div className="text-xs text-muted-foreground">
          {isConnected ? (
            <span className="flex items-center text-green-600">
              <span className="h-2 w-2 rounded-full bg-green-600 mr-1"></span>
              已连接
            </span>
          ) : (
            <span className="flex items-center text-destructive">
              <span className="h-2 w-2 rounded-full bg-destructive mr-1"></span>
              未连接
            </span>
          )}
        </div>
        
        <div className="text-xs text-muted-foreground">
          {collaborators.filter(c => c.status === 'online').length} 人在线
        </div>
      </CardFooter>
    </Card>
  );
} 